package com.hsy.sunflowerbao.base.ui.widget

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Bitmap
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import android.support.annotation.DrawableRes
import android.util.AttributeSet
import android.view.View
import android.view.ViewGroup
import android.view.animation.LinearInterpolator
import android.widget.ImageView
import android.widget.RelativeLayout

import com.scwang.smartrefresh.layout.api.RefreshFooter
import com.scwang.smartrefresh.layout.api.RefreshKernel
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.constant.RefreshState
import com.scwang.smartrefresh.layout.constant.SpinnerStyle
import com.scwang.smartrefresh.layout.internal.ProgressDrawable
import com.scwang.smartrefresh.layout.util.DensityUtil

/**
 * 经典上拉底部组件
 * Created by SCWANG on 2017/5/28.
 */

class CustomerFooter : RelativeLayout, RefreshFooter {

    /**
     * 进度控件
     */
    lateinit var progressView: ImageView
        protected set
    /**
     * RefreshKernel
     */
    protected var mRefreshKernel: RefreshKernel? = null
    /**
     * 进度图
     */
    protected var mProgressDrawable: ProgressDrawable? = null
    /**
     * 下拉效果
     */
    protected var mSpinnerStyle = SpinnerStyle.Translate
    protected var mFinishDuration = 500
    protected var mBackgroundColor = 0
    protected var mLoadmoreFinished = false
    protected var mPaddingTop = 20
    protected var mPaddingBottom = 20

    constructor(context: Context) : super(context) {
        this.initView(context, null, 0)
    }

    constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
        this.initView(context, attrs, 0)
    }

    constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
        this.initView(context, attrs, defStyleAttr)
    }

    @SuppressLint("CustomViewStyleable")
    private fun initView(context: Context, attrs: AttributeSet?, defStyleAttr: Int) {
        val density = DensityUtil()

        val lpArrow = RelativeLayout.LayoutParams(density.dip2px(20f), density.dip2px(20f))

        val lpProgress = RelativeLayout.LayoutParams(lpArrow as ViewGroup.LayoutParams)
        lpProgress.addRule(RelativeLayout.CENTER_IN_PARENT)
        progressView = ImageView(context)
        progressView.animate().interpolator = LinearInterpolator()
        addView(progressView, lpProgress)

        val ta = context.obtainStyledAttributes(attrs, com.scwang.smartrefresh.layout.R.styleable.ClassicsFooter)

        lpArrow.width = ta.getLayoutDimension(com.scwang.smartrefresh.layout.R.styleable.ClassicsHeader_srlDrawableArrowSize, lpArrow.width)
        lpArrow.height = ta.getLayoutDimension(com.scwang.smartrefresh.layout.R.styleable.ClassicsHeader_srlDrawableArrowSize, lpArrow.height)
        lpProgress.width = ta.getLayoutDimension(com.scwang.smartrefresh.layout.R.styleable.ClassicsHeader_srlDrawableProgressSize, lpProgress.width)
        lpProgress.height = ta.getLayoutDimension(com.scwang.smartrefresh.layout.R.styleable.ClassicsHeader_srlDrawableProgressSize, lpProgress.height)

        lpArrow.width = ta.getLayoutDimension(com.scwang.smartrefresh.layout.R.styleable.ClassicsHeader_srlDrawableSize, lpArrow.width)
        lpArrow.height = ta.getLayoutDimension(com.scwang.smartrefresh.layout.R.styleable.ClassicsHeader_srlDrawableSize, lpArrow.height)
        lpProgress.width = ta.getLayoutDimension(com.scwang.smartrefresh.layout.R.styleable.ClassicsHeader_srlDrawableSize, lpProgress.width)
        lpProgress.height = ta.getLayoutDimension(com.scwang.smartrefresh.layout.R.styleable.ClassicsHeader_srlDrawableSize, lpProgress.height)

        mFinishDuration = ta.getInt(com.scwang.smartrefresh.layout.R.styleable.ClassicsFooter_srlFinishDuration, mFinishDuration)
        mSpinnerStyle = SpinnerStyle.values()[ta.getInt(com.scwang.smartrefresh.layout.R.styleable.ClassicsFooter_srlClassicsSpinnerStyle, mSpinnerStyle.ordinal)]

        if (ta.hasValue(com.scwang.smartrefresh.layout.R.styleable.ClassicsFooter_srlDrawableProgress)) {
            progressView.setImageDrawable(ta.getDrawable(com.scwang.smartrefresh.layout.R.styleable.ClassicsFooter_srlDrawableProgress))
        } else {
            mProgressDrawable = ProgressDrawable()
            mProgressDrawable!!.setColor(-0x99999a)
            progressView.setImageDrawable(mProgressDrawable)
        }

        if (ta.hasValue(com.scwang.smartrefresh.layout.R.styleable.ClassicsFooter_srlPrimaryColor)) {
            setPrimaryColor(ta.getColor(com.scwang.smartrefresh.layout.R.styleable.ClassicsFooter_srlPrimaryColor, 0))
        }
        if (ta.hasValue(com.scwang.smartrefresh.layout.R.styleable.ClassicsFooter_srlAccentColor)) {
            setAccentColor(ta.getColor(com.scwang.smartrefresh.layout.R.styleable.ClassicsFooter_srlAccentColor, 0))
        }

        ta.recycle()

        if (paddingTop == 0) {
            if (paddingBottom == 0) {
                setPadding(paddingLeft,  density.dip2px(20f), paddingRight,  density.dip2px(20f))
            } else {
                setPadding(paddingLeft,  density.dip2px(20f), paddingRight,  paddingBottom)
            }
        } else {
            if (paddingBottom == 0) {
                setPadding(paddingLeft,  paddingTop, paddingRight,  density.dip2px(20f))
            } else {
                mPaddingTop = paddingTop
                mPaddingBottom = paddingBottom
            }
        }
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        if (View.MeasureSpec.getMode(heightMeasureSpec) == View.MeasureSpec.EXACTLY) {
            setPadding(paddingLeft, 0, paddingRight, 0)
        } else {
            setPadding(paddingLeft, mPaddingTop, paddingRight, mPaddingBottom)
        }
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
    }

    override fun onInitialized(kernel: RefreshKernel, height: Int, extendHeight: Int) {
        mRefreshKernel = kernel
        mRefreshKernel!!.requestDrawBackgroundForFooter(mBackgroundColor)
    }

    override fun isSupportHorizontalDrag(): Boolean {
        return false
    }

    override fun onHorizontalDrag(percentX: Float, offsetX: Int, offsetMax: Int) {}

    override fun onPulling(percent: Float, offset: Int, footerHeight: Int, extendHeight: Int) {

    }

    override fun onReleasing(percent: Float, offset: Int, headHeight: Int, extendHeight: Int) {

    }

    override fun onReleased(layout: RefreshLayout, footerHeight: Int, extendHeight: Int) {
        if (!mLoadmoreFinished) {
            progressView.visibility = View.VISIBLE
            if (mProgressDrawable != null) {
                mProgressDrawable!!.start()
            } else {
                progressView.animate().rotation(36000f).duration = 100000
            }
        }
    }


    override fun onStartAnimator(layout: RefreshLayout, headHeight: Int, extendHeight: Int) {

    }

    override fun onFinish(layout: RefreshLayout, success: Boolean): Int {
        if (!mLoadmoreFinished) {
            if (mProgressDrawable != null) {
                mProgressDrawable!!.stop()
            } else {
                progressView.animate().rotation(0f).duration = 10
            }
            return mFinishDuration
        }
        return 0
    }

    /**
     * ClassicsFooter 在(SpinnerStyle.FixedBehind)时才有主题色
     */
    @Deprecated("")
    override fun setPrimaryColors(vararg colors: Int) {
        if (mSpinnerStyle == SpinnerStyle.FixedBehind) {
            if (colors.isNotEmpty()) {
                if (background !is BitmapDrawable) {
                    setPrimaryColor(colors[0])
                }
                if (colors.size > 1) {
                    setAccentColor(colors[1])
                } else {
                    setAccentColor(if (colors[0] == -0x1) -0x99999a else -0x1)
                }
            }
        }
    }

    /**
     * 设置数据全部加载完成，将不能再次触发加载功能
     */
    override fun setNoMoreData(noMoreData: Boolean): Boolean {
        if (mLoadmoreFinished != noMoreData) {
            mLoadmoreFinished = noMoreData
            if (mProgressDrawable != null) {
                mProgressDrawable!!.stop()
            } else {
                progressView.animate().rotation(0f).duration = 10
            }
            progressView.visibility = View.GONE
        }
        return true
    }

    override fun getView(): View {
        return this
    }

    override fun getSpinnerStyle(): SpinnerStyle {
        return mSpinnerStyle
    }

    override fun onStateChanged(refreshLayout: RefreshLayout, oldState: RefreshState, newState: RefreshState) {
        if (!mLoadmoreFinished) {
            when (newState) {
                RefreshState.None, RefreshState.PullUpToLoad -> {
                    progressView.visibility = View.VISIBLE
                }
                RefreshState.Refreshing -> {

                    progressView.visibility = View.GONE
                }
                else -> {
                }
            }
        }
    }

    fun setProgressBitmap(bitmap: Bitmap): CustomerFooter {
        mProgressDrawable = null
        progressView.setImageBitmap(bitmap)
        return this
    }

    fun setProgressDrawable(drawable: Drawable): CustomerFooter {
        mProgressDrawable = null
        progressView.setImageDrawable(drawable)
        return this
    }

    fun setProgressResource(@DrawableRes resId: Int): CustomerFooter {
        mProgressDrawable = null
        progressView.setImageResource(resId)
        return this
    }

    fun setSpinnerStyle(style: SpinnerStyle): CustomerFooter {
        this.mSpinnerStyle = style
        return this
    }

    fun setAccentColor(accentColor: Int): CustomerFooter {
        if (mProgressDrawable != null) {
            mProgressDrawable!!.setColor(accentColor)
        }
        return this
    }

    fun setPrimaryColor(primaryColor: Int): CustomerFooter {
        setBackgroundColor(primaryColor)
        if (mRefreshKernel != null) {
            mRefreshKernel!!.requestDrawBackgroundForFooter(mBackgroundColor)
        }
        return this
    }

    fun setFinishDuration(delay: Int): CustomerFooter {
        mFinishDuration = delay
        return this
    }

    fun setTextSizeTitle(size: Float): CustomerFooter {
        if (mRefreshKernel != null) {
            mRefreshKernel!!.requestRemeasureHeightForFooter()
        }
        return this
    }

    fun setTextSizeTitle(unit: Int, size: Float): CustomerFooter {
        if (mRefreshKernel != null) {
            mRefreshKernel!!.requestRemeasureHeightForFooter()
        }
        return this
    }

    fun setDrawableMarginRight(dp: Float): CustomerFooter {
        return setDrawableMarginRightPx(DensityUtil.dp2px(dp))
    }

    fun setDrawableMarginRightPx(px: Int): CustomerFooter {
        val lpProgress = progressView.layoutParams as ViewGroup.MarginLayoutParams
        progressView.layoutParams = lpProgress
        return this
    }

    fun setDrawableSize(dp: Float): CustomerFooter {
        return setDrawableSizePx(DensityUtil.dp2px(dp))
    }

    fun setDrawableSizePx(px: Int): CustomerFooter {
        val lpProgress = progressView.layoutParams
        progressView.layoutParams = lpProgress
        return this
    }

    fun setDrawableProgressSize(dp: Float): CustomerFooter {
        return setDrawableProgressSizePx(DensityUtil.dp2px(dp))
    }

    fun setDrawableProgressSizePx(px: Int): CustomerFooter {
        val lpProgress = progressView.layoutParams
        lpProgress.width = px
        lpProgress.height = px
        progressView.layoutParams = lpProgress
        return this
    }
}